package com.jrx.anytxn.param.controller.api;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.dto.partner.PartnerLimitAdjustmentReq;
import com.jrx.anytxn.param.dto.partner.PartnerLimitAdjustmentRes;
import com.jrx.anytxn.param.service.partner.IPartnerGeneralService;
import com.jrx.anytxn.redisson.service.RedissonLockService;
import com.jrx.anytxn.redisson.util.LockType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Api(tags = "合作方相关接口")
@RestController
@RequestMapping(value = "/api/param/partner")
public class PartnerController {

    private static final Logger logger = LoggerFactory.getLogger(PartnerController.class);

    @Autowired
    private RedissonLockService redissonLockService;
    @Autowired
    private IPartnerGeneralService partnerGeneralService;

    @ApiOperation(value = "合作方额度调整", notes = "合作方额度调整API")
    @PostMapping(value = "/partnerLimitAdjustment")
    public TxnRespResult<PartnerLimitAdjustmentRes> partnerLimitAdjustment(@Valid @RequestBody PartnerLimitAdjustmentReq req) throws Exception {
        String lockKey = String.format(Constant.PARTNER_REDIS_LOCK, req.getTenantId(), req.getPartnerId());
        RLock lock = redissonLockService.getRLock(lockKey, LockType.REENTRANT_LOCK);
        try {
            // 获取redis锁
            boolean lockFlag = lock.tryLock(Constant.INVESTOR_REDIS_LOCK_WAITE_TIME, Constant.INVESTOR_REDIS_LOCK_LESS_TIME, TimeUnit.SECONDS);
            if (!lockFlag) {
                logger.error(TxnRespCode.TRANSACTION_PROCESSING.getMsg());
                throw new TxnBizException(TxnRespCode.TRANSACTION_PROCESSING.getCode(), TxnRespCode.TRANSACTION_PROCESSING.getMsg());
            }

            TxnRespResult<PartnerLimitAdjustmentRes> result = new TxnRespResult<>();
            PartnerLimitAdjustmentRes res = partnerGeneralService.partnerLimitAdjustment(req);
            logger.debug("合作方额度调整结束endTime{}",result.getEndTime());
            result = result.getSuccess(res);
            return result;
        } catch (InterruptedException e) {
            String msg = String.format(Constant.GET_REDIS_LOCK_ERROR, lockKey);
            logger.error("异常信息{}", e);
            throw new TxnException(msg);
        } finally {
            lock.unlock();
        }
    }
}
